package
{
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.sampler.NewObjectSample;
	import flash.ui.Keyboard;
	import flash.utils.ByteArray;
	
	public class Game extends MovieClip
	{
		var myPlatform:Platform=new Platform();
		var myPlatform2:Platform=new Platform();
		var mainCharacter:character=new character();
		var platformArray:Array=new Array();
		var isJumpAllowed:Boolean = false;
		public function Game()
		{
			super();
			myPlatform.x = stage.stageWidth/2;
			myPlatform.y = stage.stageHeight/2;
			myPlatform2.x = 100;
			myPlatform2.y = 100;

			mainCharacter.x = stage.stageWidth/2;
			mainCharacter.y = stage.stageHeight/2-100;
			mainCharacter.vy = 0;
			mainCharacter.vx = 0;
			stage.addChild(myPlatform);
			stage.addChild(myPlatform2);
			stage.addChild(mainCharacter);
			stage.addEventListener(MouseEvent.CLICK, addPlatform);
			stage.addEventListener(KeyboardEvent.KEY_DOWN,moveCharacter);
			stage.addEventListener(KeyboardEvent.KEY_UP,stopCharacter);
			stage.addEventListener(Event.ENTER_FRAME, updater);
			platformArray.push(myPlatform);
			platformArray.push(myPlatform2);
		}
		
		public function moveCharacter(e:KeyboardEvent):void
		{
			switch(e.keyCode)
			{
				case Keyboard.LEFT:
					mainCharacter.vx=-10;
					break;
				case Keyboard.RIGHT:
					mainCharacter.vx=10;
					break;
				case Keyboard.SPACE:
					if(isJumpAllowed)
					{
						mainCharacter.vy=-20;
					}
					isJumpAllowed=false;
					break;
			}
		}
		public function clone(source:Object):*{
			var byteArray:ByteArray = new ByteArray();
			byteArray.writeObject(source);
			byteArray.position = 0;
			return(byteArray.readObject());
		}
		public function addPlatform(e:MouseEvent):void
		{
			var anotherPlatform:Platform=new Platform();
			anotherPlatform.x=e.stageX;
			anotherPlatform.y=e.stageY;
			
			platformArray.push(anotherPlatform);
			stage.addChild(anotherPlatform);
		}
		
		public function updater(e:Event):void
		{
			for(var i:int=0;i<platformArray.length;i+=1)
			{
				if(platformArray[i].hitTestPoint(mainCharacter.x,mainCharacter.y,true))
				{
					isJumpAllowed=true;
					mainCharacter.vy=0;
					mainCharacter.isOnPlatform=true;
					while(platformArray[i].hitTestPoint(mainCharacter.x,mainCharacter.y,true))
					{
						mainCharacter.y-=.002 ;
						mainCharacter.vy=0;
					}
					//mainCharacter.y = myPlatform.y-myPlatform.height/2
				}
				else
				{
					mainCharacter.vyAcceleration();
					mainCharacter.isOnPlatform=false;
				}
			}
		}
		
		public function stopCharacter(e:KeyboardEvent):void
		{
			switch(e.keyCode)
			{
				case Keyboard.LEFT:
				case Keyboard.RIGHT:
					mainCharacter.vx=0;
					break;
			}

		}
		
	}
}